package org.vaadin.nf4v.ext.config.param;

import org.vaadin.nf4v.core.config.AbstractConfig;
import org.vaadin.nf4v.core.config.ContextConfig;
import org.vaadin.nf4v.core.config.ContextConfigurationException;
import org.vaadin.nf4v.core.config.PageConfig;
import org.vaadin.nf4v.core.config.process.NavigationConfigProcessor;
import org.vaadin.nf4v.core.config.process.parser.ContextConfigParser;
import org.vaadin.nf4v.core.config.process.parser.PageConfigParser;
import org.vaadin.nf4v.ext.config.util.AnnotationUtil;

/**
 * Configuration extension:
 * Scans window and page classes for @Param annotation and sets configuration parameter.
 */
public class ParamAnnotationParser implements ContextConfigParser, PageConfigParser {

    @Override
    public void parse(NavigationConfigProcessor navigationConfigProcessor, ContextConfig contextConfig)
            throws ContextConfigurationException {
        setParam(contextConfig, contextConfig.getWindowClass());
    }

    @Override
    public void parse(NavigationConfigProcessor navigationConfigProcessor, ContextConfig contextConfig, PageConfig pageConfig)
            throws ContextConfigurationException {
        setParam(pageConfig, pageConfig.getPageClass());
    }

    protected void setParam(AbstractConfig config, Class clazz) throws ContextConfigurationException{
        Param ann = AnnotationUtil.getClassAnnotation(Param.class, clazz);
        if (ann != null) {
            if (ann.key() == null) {
                throw new ContextConfigurationException("Parameter key not specified in @Param annotation " +
                        "of class " + clazz);
            }
            if (ann.value() == null) {
                throw new ContextConfigurationException("Parameter value not specified in @Param annotation " +
                        "of class " + clazz);
            }
            config.setParam(ann.key(), ann.value());
        }
    }
}
